package com.yuexiao.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.yuexiao.entity.ResultInfo;
import com.yuexiao.pojo.Employee;
import com.yuexiao.pojo.User;
import com.yuexiao.service.EmployeeService;
import com.yuexiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

/**
 * 登录成功时调用
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Reference
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {


        String phone = "";
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            phone = ((UserDetails) principal).getUsername();
        }
        if (principal instanceof Principal) {
            phone = ((Principal) principal).getName();
        }

        //清除redis中验证码
        //redisUtil.del(phone);

        User userByPhone = userService.getUserByPhone(phone);

        httpServletRequest.getSession().setAttribute("userid",userByPhone.getId());
        redisUtil.set("loginId",userByPhone.getId());

        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(200);
        httpServletResponse.getWriter().write(JSON.toJSONString(ResultInfo.success(userByPhone)));
    }
}